import React, { Component, Fragment, createRef } from 'react'
import { Button, Form, Input, Checkbox, message } from 'antd'
import './login.scss'
import { login } from '_api'

export default class Home extends Component {
  constructor (props) {
    super(props)
    this.formInstance = createRef()
  }
  render() {
    return (
      <Fragment>
        <div className="login_container">
          <div className="login_box">
            {/* 头像 */}
            <div className="avatar_box">
              <img
                src="../../assets/imgs/sakura.jpg"
                alt="图片不见惹！"
              />
            </div>
            {/* 登录表单 */}
            <Form
              ref={this.formInstance}
              className="login_form"
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              onFinish={this.onFinish}
              autoComplete="off"
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
                <Checkbox>记住密码</Checkbox>
              </Form.Item>

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit" style={{marginRight: 50}}>
                  Submit
                </Button>
                <Button htmlType="button" onClick={this.onReset}>
                  Reset
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </Fragment>
    )
  };
  // 提交表单
  onFinish = (form) => {
    login(form).then(res => {
      if (res.data.code === 200) {
        sessionStorage.setItem('token', res.data.data.token)
        sessionStorage.setItem('role', res.data.data.role)
        sessionStorage.setItem('userinfo', JSON.stringify(res.data.data.userinfo))
        message.success(res.data.msg, 1 ,() => {
          this.props.history.replace('/admin')
        })
      }
    })
  }
  // 重置表单
  onReset = () => {
    this.formInstance.current.resetFields();
  }
}
